package goclient

import (
	"github.com/gorilla/websocket"
	"net/http"
	"time"
)

func NewWebsocketClient() *WebsocketClient {
	return &WebsocketClient{dialer: &websocket.Dialer{
		Proxy:            http.ProxyFromEnvironment,
		HandshakeTimeout: 30 * time.Second,
		ReadBufferSize:   2048,
		WriteBufferSize:  2048,
	}}
}

func NewKcpWebsocketClient() *WebsocketClient {
	return &WebsocketClient{dialer: &websocket.Dialer{
		Proxy:            http.ProxyFromEnvironment,
		HandshakeTimeout: 30 * time.Second,
		NetDialContext:   kcpDialContext,
		ReadBufferSize:   2048,
		WriteBufferSize:  2048,
	}}
}

type WebsocketClient struct {
	dialer *websocket.Dialer
}

func (c *WebsocketClient) Dial(url string) (*WebsocketConn, error) {
	conn, _, err := c.dialer.Dial(url, nil)
	if err != nil {
		return nil, err
	}
	return &WebsocketConn{conn: conn}, nil
}

func (c *WebsocketClient) DialWithHeader(url string, header *Header) (*WebsocketConn, error) {
	var h http.Header = nil
	if header != nil {
		h = *header.header
	}
	conn, _, err := c.dialer.Dial(url, h)
	if err != nil {
		return nil, err
	}
	return &WebsocketConn{conn: conn}, nil
}
